//
//  SXPictureViewController.swift
//  sina
//
//  Created by shengxinwei on 16/5/29.
//  Copyright © 2016年 shengxinwei. All rights reserved.
//

import UIKit
import HMImagePicker

private let reuseIdentifier = "Cell"

//定义显示图片的信息
private let colCount: CGFloat = 4
private let margin: CGFloat = 3
//设置上传最大张数
private let maxImageCount: Int = 4

private let itemWith: CGFloat = (ScreenWidth - (colCount+1) * margin)/4

class SXPictureViewController: UICollectionViewController {
    
    //定义图片数组
    lazy var images: [UIImage] = [UIImage]()
    //声明数组
    lazy var selectedAsset: [PHAsset] = [PHAsset]()

    
    init() {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(itemWith, itemWith)
        layout.sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin)
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        
        super.init(collectionViewLayout: layout)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView?.backgroundColor = UIColor.whiteColor()
        // Register cell classes
        self.collectionView!.registerClass(SXPictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        // Do any additional setup after loading the view.
    }
    
    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let detla = images.count == maxImageCount ? 0 : 1
        return images.count + detla
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SXPictureSelectorCell
        cell.backgroundColor = UIColor.redColor()
        if indexPath.item == images.count {
            cell.image = nil
        }else {
            cell.image = images[indexPath.item]
        }
        cell.pictureDeleagte = self
        return cell
    }
    
    
}

extension SXPictureViewController: HMImagePickerControllerDelegate {
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        
        // 记录图像，方便在 CollectionView 显示
        self.images = images;
        // 记录选中资源集合，方便再次选择照片定位
         self.selectedAsset = selectedAssets!
        self.collectionView?.reloadData()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

//实现代理
extension SXPictureViewController: pictureSelectorDelegate  {
    
    func userWillAddPicture() {
        //iOS8.0 之后对用户隐私进行保护,,需要在用户同意的情况下,应用才能访问相册
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
            return
        }
       
        let picker = HMImagePickerController(selectedAssets: selectedAsset)
        picker.pickerDelegate = self
        picker.targetSize = CGSize(width: 600, height: 600)
        picker.maxPickerCount = maxImageCount
        presentViewController(picker, animated: true, completion: nil)
     
        
//        HMImagePickerController *picker = [[HMImagePickerController alloc] initWithSelectedAssets:self.selectedAssets];
//        
//        // 设置图像选择代理
//        picker.pickerDelegate = self;
//        // 设置目标图片尺寸
//        picker.targetSize = CGSizeMake(600, 600);
//        // 设置最大选择照片数量
//        picker.maxPickerCount = 9;
//        
//        [self presentViewController:picker animated:YES completion:nil];
        
        
        //系统的代理
//        let picker = UIImagePickerController()
//        //设置代理
//        picker.delegate = self
//        
//        self.presentViewController(picker, animated: true, completion: nil)
    }
    
    func userWillDeletePicture(cell: SXPictureSelectorCell) {
        print("delete")
        guard let indexPath = collectionView?.indexPathForCell(cell) else {
            return
        }
        
        images.removeAtIndex(indexPath.item)
        selectedAsset.removeAtIndex(indexPath.item)
        collectionView?.reloadData()
        
    }
}

extension SXPictureViewController: UINavigationControllerDelegate,UIImagePickerControllerDelegate {
    //实现选择图片的协议方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print(image)
//        print("---------------")
//        print(editingInfo)
        //保存图片 添加到数组
        images.append(image)
        self.collectionView?.reloadData()
        //实现了协议方法之后 视图控制器的dismiss 就交给了程序员
        dismissViewControllerAnimated(true, completion: nil)
    }
}



@objc protocol pictureSelectorDelegate: NSObjectProtocol {
    //定义协议方法
    optional func userWillAddPicture()
    
    optional func userWillDeletePicture(cell: SXPictureSelectorCell)
}


//MARK: - 自定义cell
class SXPictureSelectorCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet {
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    weak var pictureDeleagte: pictureSelectorDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupCell()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupCell() {
        contentView.addSubview(addBtn)
        addBtn.addSubview(deleteBtn)
        
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(addBtn)
            
        }
        
        //添加按钮的点击事件
        addBtn.addTarget(self, action: #selector(SXPictureSelectorCell.addBtnDidClick), forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: #selector(SXPictureSelectorCell.deleteBtnDidClick), forControlEvents: .TouchUpInside)
    }
    
    @objc private func addBtnDidClick() {
        pictureDeleagte?.userWillAddPicture?()
        
    }
    
    @objc private func deleteBtnDidClick() {
        pictureDeleagte?.userWillDeletePicture?(self)
        
    }
    
    
    //MARK: - 懒加载
    //添加按钮
    private lazy var addBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage.init(named: "compose_pic_add"), forState: .Normal)
        btn.setBackgroundImage(UIImage.init(named: "compose_pic_add_highlighted"), forState: .Highlighted)
        
        return  btn
    }()
    
    //删除按钮
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"compose_photo_close"), forState: .Normal)
        return btn
    }()
    
}
